import { pathOr } from 'ramda';
import { AVILIABLE_TASK_MAP } from '../../../common/constants';

const defaultValues = {
	StatusId: null,
	SecurityStatus: 'unknown',
	PrevResultId: null,
	ResultId: null,
	Abnormal: false,
	IsStarted: false,
	AlertState: {
		securityStatus: 'unknown',
		firstSendTime: null,
		lastSendTime: null,
		sendCount: 0,
	},
	NextExecDate: null,
};
/**
 * 初始化可用性任务关联字段数据
 */
export default function fillAviliableFieldDefaultValue({ record, prevRecord }) {
	Object.keys(AVILIABLE_TASK_MAP).forEach(type => {
		const len = record[`${type}Settings`].length || 0;

		const changedIdx = Array(len).fill(true);
		if (prevRecord) {
			record[`${type}Settings`].forEach((settings, i) => {
				const prevSettings = prevRecord[`${type}Settings`][i];
				if (prevSettings && prevSettings.target === settings.target) {
					changedIdx[i] = false;
				}
			});
		}

		Object.entries(defaultValues).forEach(([fieldSuffix, defaultValue]) => {
			const field = `${type}${fieldSuffix}`;
			const currentValue = record[field];

			if (prevRecord) {
				record[field] = Array.from(Array(len)).map((_, i) => {
					if (changedIdx[i]) return defaultValue;
					return pathOr(defaultValue, [field, i], prevRecord);
				});
				return;
			} else if (currentValue?.length === len) {
				// 长度没有改变，假设没有做修改
				return;
			}

			record[field] = Array(len).fill(defaultValue);
		});
	});

	return record;
}
